import hashlib
import json
import math
import time
from enum import Enum
import pandas as pd
import requests
import os
import datetime
from flask import jsonify


def boku_rg(file, form):
    # 1、先把文件保存到服务器，再判断文件内容是否符合条件
    filename = file.filename
    # 使用当前时间戳作为文件名的一部分，避免文件名冲突
    filename = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + '_' + filename
    with open(f"./tmp/{filename}", mode="wb") as f:
        f.write(file.stream.read())
        print(f"{filename}保存完毕！")
    # 1-2 读取文件内容
    excel_data = []
    try:
        df = pd.read_excel(f"./tmp/{filename}")
        header = df.columns.tolist()
        if(header != ['订单号', '书号', '书名', '数量', '物流单号', '快递公司']):
            return {'message': 'Excel文件内容不正确！', 'code': 400}
        for index, row in df.iterrows():
            row_data = {}
            row_data['orderNum'] = str(row['订单号'])
            row_data['isbn'] = str(row['书号'])
            row_data['bookName'] = row['书名']
            row_data['num'] = int(row['数量'])
            row_data['logisticsNum'] = str(row['物流单号'])
            row_data['logisticsCompany'] = row['快递公司']
            excel_data.append(row_data)
        # print(excel_data)
    except Exception as e:
        return {'message': f'读取Excel文件出错！错误原因：{e}', 'code': 400}
    finally:
        os.remove(f"./tmp/{filename}")
    # 1、先登录
    step2 = boku_login(form)
    # 2-1、有值说明登录失败
    if step2 != None:
        return step2
    # 3、调用接口退货
    return {'message': '退货成功！','data': boku_ret(excel_data, form.get('type')), 'code': 200}

def boku_ret(data, apitype):
    retData = []
    # 循环data
    for item in data:
        print(item)
        params = common_params()
        data = {
            'timestamp': f'{int(time.time())}',
            'method': 'order.list.completed',
            'appkey': '10010',
            'data': f'{{"page": 1, "page_size": 10, "start_time": "", "end_time": "", "order_status": "all", "outer_id": "%s"}}' % item['orderNum'],
        }
        data['sign'] = get_sign(data)
        response = requests.post('http://fenxiao.bookuu.com/frontapi/', cookies=params['cookies'],
                                 headers=params['headers'], data=data, verify=False)
        res_json = json.loads(response.text)
        if (int(apitype) == 1):
            if (res_json['info']['count'] != "0"):
                a_row = res_json['info']['list'][0]
                if a_row['son'] is not None and len(a_row['son']) != 0:
                    correct_item = find_correct_item(a_row['son'], item['isbn'])
                    if(correct_item == {}):
                        retData.append({'status': 5, 'orderInfo': item})
                    elif(correct_item.get('after_status') == '发起售后'):
                        srgRet = start_return_goods(item, correct_item.get('spbs'), a_row['id'])
                        retData.append({'status': 1, 'orderInfo': srgRet})
                    elif(correct_item.get('after_status') == '退款中'):
                        srgRet = step4_return_goods(item, correct_item.get('spbs'), a_row['id'], correct_item.get('after_id'))
                        retData.append({'status': 1, 'orderInfo': srgRet})
                    elif(correct_item.get('after_status') == '退款成功'):
                        item['message'] = '退款成功'
                        retData.append({'status': 4, 'orderInfo': item})
                    else:
                        item['message'] = '未知错误'
                        retData.append({'status': 6, 'orderInfo': item})
                else:
                    item['message'] = '未找到子订单号'
                    retData.append({'status': 0, 'orderInfo': item})
            else:
                item['message'] = '未找到订单号'
                retData.append({'status': 0, 'orderInfo': item})
        else:
            if (res_json['info']['count'] != "0"):
                a_row = res_json['info']['list'][0]
                if a_row['son'] is not None and len(a_row['son']) != 0:
                    correct_item = find_correct_item(a_row['son'], item['isbn'])
                    if(correct_item == {}):
                        item['after_status'] = '在订单里没有找到该书号对应数据'
                        retData.append({'status': 5, 'orderInfo': item})
                    else:
                        item['after_status'] = correct_item.get('after_status')
                        retData.append({'status': 5, 'orderInfo': item})
                else:
                    item['after_status'] = '未找到该单号'
                    retData.append({'status': 0, 'orderInfo': item})
            else:
                item['after_status'] = '未找到该单号'
                retData.append({'status': 0, 'orderInfo': item})

    return retData
    # 暂无数据(0)、发起售后(1)、退款中未填单号(2)、退款中已填单号(3)、退款成功(4)、在订单里没有找到该书号对应数据(5)、未知错误(6)
def start_return_goods(item, spbs, bookuu_id):
    params = common_params()
    data = {
        'timestamp': f'{int(time.time())}',
        'method': 'order.aftersale.get',
        'appkey': '10010',
        'data': f'{{"bookuu_id":"{bookuu_id}","spbs":"{spbs}"}}',
    }
    data['sign'] = get_sign(data)
    response = requests.post('http://fenxiao.bookuu.com/frontapi/', cookies=params['cookies'],
                             headers=params['headers'], data=data, verify=False)
    res_json = json.loads(response.text)
    print(res_json["info"]["list"])
    if "info" in res_json and "list" in res_json["info"] and "xsj" in res_json["info"]["list"] and \
            res_json["status"] == '1':
        # return res_json["info"]["list"]
        secInfo = res_json["info"]["list"]
        # 退货第一步
        data = {
            'timestamp': f'{int(time.time())}',
            'method': 'order.aftersale.add',
            'appkey': '10010',
            'data': f'{{"type":"2","reason_type":1,"apply_money":"{float(secInfo["xsj"]) * int(item["num"])}",'
                    f'"apply_count":{item["num"]},"content":"退货退款","image":"","spbs":"{spbs}","ord'
                    f'er_id":"{bookuu_id}"}}',
        }
        data['sign'] = get_sign(data)
        response = requests.post('http://fenxiao.bookuu.com/frontapi/', cookies=params['cookies'],
                                 headers=params['headers'], data=data, verify=False)
        res_json = json.loads(response.text)
        if "status" in res_json and res_json["status"] == '1':
            # 退货第二步填写单号
            after_id = res_json["info"][0]
            data = {
                'timestamp': f'{int(time.time())}',
                'method': 'order.aftersale.reback',
                'appkey': '10010',
                'data': f'{{"bookuu_id":"{bookuu_id}","after_id":"{after_id}","express_company":"{item["logisticsCompany"]}","express_number":"{item["logisticsNum"]}","is_unified":false}}',
            }
            data['sign'] = get_sign(data)
            response = requests.post('http://fenxiao.bookuu.com/frontapi/', cookies=params['cookies'],
                                     headers=params['headers'], data=data, verify=False)
            res_json = json.loads(response.text)
            if "status" in res_json and res_json["status"] == '1':
                item['message'] = "退货成功！"
                return item
            elif "status" in res_json and "message" in res_json and res_json["message"] == '不处于可退包状态!':
                item['message'] = "不处于可退包状态！"
                return item
            else:
                item['message'] = "退货第二步填写单号失败！"
                return item
        else:
            item['message'] = "退货第一步失败"
            return item
    else:
        # 返回完整的item信息并且在item里message属性：值为“获取商品信息失败”
        item['message'] = "获取商品信息失败"
        return item

def step4_return_goods(item, spbs, bookuu_id, after_id):
    params = common_params()
    data = {
        'timestamp': f'{int(time.time())}',
        'method': 'order.aftersale.get',
        'appkey': '10010',
        'data': f'{{"bookuu_id":"{bookuu_id}","spbs":"{spbs}", "after_id": "{after_id}"}}',
    }
    data['sign'] = get_sign(data)
    response = requests.post('http://fenxiao.bookuu.com/frontapi/', cookies=params['cookies'],
                             headers=params['headers'], data=data, verify=False)
    res_json = json.loads(response.text)
    if "info" in res_json and "list" in res_json["info"] and "log" in res_json["info"]["list"] and len(res_json["info"]["list"]["log"]) == 3:
        data = {
            'timestamp': f'{int(time.time())}',
            'method': 'order.aftersale.reback',
            'appkey': '10010',
            'data': f'{{"bookuu_id":"{bookuu_id}","after_id":"{after_id}","express_company":"{item["logisticsCompany"]}","express_number":"{item["logisticsNum"]}","is_unified":false}}',
        }
        data['sign'] = get_sign(data)
        response = requests.post('http://fenxiao.bookuu.com/frontapi/', cookies=params['cookies'],
                                 headers=params['headers'], data=data, verify=False)
        res_json = json.loads(response.text)
        if "status" in res_json and res_json["status"] == '1':
            item['message'] = "退货成功！"
            return item
        elif "status" in res_json and "message" in res_json and res_json["message"] == '不处于可退包状态!':
            item['message'] = "不处于可退包状态！"
            return item
        else:
            print(data['data'])
            print(res_json)
            item['message'] = "退货第二步填写单号失败！"
            return item
    elif "info" in res_json and "list" in res_json["info"] and "log" in res_json["info"]["list"] and len(res_json["info"]["list"]["log"]) == 5 and "content" in res_json["info"]["list"]["log"][4] and "order_state" in res_json["info"]["list"]["log"][4]["content"] and res_json["info"]["list"]["log"][4]["content"]["order_state"] == "已发货":
        item['message'] = "退款中"
        return item
    else:
        item['message'] = "本单已经申请退款，但是获取退货信息失败，请手动确认！"
        return item
def boku_login(form):
    username = form.get('username')
    password = form.get('password')
    params = common_params()
    data = {
        'timestamp': f'{int(time.time())}',
        'method': 'account.passport.login',
        'appkey': '10010',
        'data': f'{{"recall":"0","uname":"{username}","password":"{password}"}}',
    }
    data['sign'] = get_sign(data)
    response = requests.post('http://fenxiao.bookuu.com/frontapi/', cookies=params['cookies'],
                             headers=params['headers'], data=data, verify=False)
    res_json = json.loads(response.text)
    # print(res_json)
    if res_json['status'] != '1':
        return res_json

def common_params():
    return {
        'cookies': {
            'href': 'http%3A%2F%2Ffenxiao.bookuu.com%2F%23%2Forder%2FtoDeliver',
            'PHPSESSID': 'onceduhjcq8s416ts8bth0irh0',
            '_ati': '4534430205943',
            'accessId': '92464560-3f16-11e9-8a25-8d8585556f17',
            'uuid_92464560-3f16-11e9-8a25-8d8585556f17': '72b903aa-f9e1-4658-aa9b-f125a4f93fe4',
            'pageViewNum': '1',
        },
        'headers': {
            'Accept': 'application/json, text/plain, */*',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'no-cache',
            'Content-Type': 'application/x-www-form-urlencoded',
            # 'Cookie': 'href=http%3A%2F%2Ffenxiao.bookuu.com%2F%23%2Forder%2FtoDeliver; PHPSESSID=onceduhjcq8s416ts8bth0irh0; _ati=4534430205943; accessId=92464560-3f16-11e9-8a25-8d8585556f17; uuid_92464560-3f16-11e9-8a25-8d8585556f17=72b903aa-f9e1-4658-aa9b-f125a4f93fe4; pageViewNum=43',
            'Origin': 'http://fenxiao.bookuu.com',
            'Pragma': 'no-cache',
            'Proxy-Connection': 'keep-alive',
            'Referer': 'http://fenxiao.bookuu.com/',
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
        },
    }


def get_sign(data):
    e = ""
    for key in sorted(data.keys()):
        e += str(key) + str(data[key])
    e = "424b11b3968edd75f2b4a147471cbb45" + e + "424b11b3968edd75f2b4a147471cbb45"
    md5_hash = hashlib.md5()
    md5_hash.update(e.encode('utf-8'))
    return md5_hash.hexdigest().upper()

def find_correct_item(son_list, isbn):
    for son_item in son_list:
        if son_item.get('isbn')[:13] == isbn[:13]:
            return son_item
    return {}
